package cn.asura.utils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Asura
 * @description
 * @createTime 2020-09-18 23:10
 */
public class FileUpLoadUtil {
    public static String fileUpload(HttpServletRequest request, MultipartFile imgFile) {
        String realPath = getRealPath(request);
        InputStream inputStream = null;
        String fileName = "";
        try {
            inputStream = imgFile.getInputStream();
            String originalFilename = imgFile.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            // 防止文件重名及覆盖
            fileName = UUID.randomUUID().toString() + "." + extension;
            IOUtils.copy(inputStream, new FileOutputStream(new File(realPath, fileName)));
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload/" + fileName;
    }

    private static String getRealPath(HttpServletRequest request) {
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        File file = new File(realPath);
        if (!file.exists()) {
            @SuppressWarnings("unused")
            boolean success = file.mkdirs();
        }
        return realPath;
    }
}
